package com.easpeed.comon.database

import android.content.Context
import androidx.annotation.NonNull
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.easpeed.comon.database.bean.CommonDataSqlBean
import com.easpeed.comon.database.bean.CrashBean
import com.easpeed.comon.database.dao.CommonDataDao
import com.easpeed.comon.database.dao.CrashDao

@Database(
    entities = [
        CommonDataSqlBean::class,
        CrashBean::class
    ],
    version = 4,
    exportSchema = true
)
abstract class DataBaseCommon : RoomDatabase() {
    companion object {
        private val DBNAME = "database_by.db"

        //创建单例
        @Volatile
        private var instance: DataBaseCommon? = null

        @Synchronized
        fun getInstance(): DataBaseCommon {
            if (instance == null) {
                throw RuntimeException("请在Application中初始化数据库")
            }
            return instance!!
        }

        public fun init(context: Context) {
            if (instance == null) {
                instance = create(context)
            }
        }

        /**
         * 创建数据库 */
        private fun create(context: Context): DataBaseCommon {
            return Room.databaseBuilder(context, DataBaseCommon::class.java, DBNAME)
                //允许在主线程操作数据库，一般不推荐；设置这个后主线程调用增删改查不会报错，否则会报错
                .allowMainThreadQueries()
                //该方法能在升级异常重新创建数据库，但所有的数据都会丢失
//                .fallbackToDestructiveMigration()
                .addMigrations(object : Migration(2, 3) {
                    override fun migrate(@NonNull database: SupportSQLiteDatabase) {
                        database.execSQL(
                            "CREATE TABLE IF NOT EXISTS `table_common` (" +
                                    "`loginName` TEXT DEFAULT NULL," +
                                    "`dataType` TEXT DEFAULT NULL," +
                                    "`json` TEXT DEFAULT NULL," +
                                    "`createTimeMills` INTEGER NOT NULL," +
                                    "`updateTimeMills` INTEGER NOT NULL," +
                                    "`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL" +
                                    ")"
                        )
                    }
                })
                .addMigrations(object : Migration(3, 4) {
                    override fun migrate(@NonNull database: SupportSQLiteDatabase) {
                    }
                })
                .build()
        }
    }

    abstract fun getCommonDataDao(): CommonDataDao?

    //这个是必要的，创建DAO的抽象类
    abstract fun getCrashDao(): CrashDao?

}